#include "execution/executors/sort_executor.h"

namespace bustub {

SortExecutor::SortExecutor(ExecutorContext *exec_ctx, const SortPlanNode *plan,
                           std::unique_ptr<AbstractExecutor> &&child_executor)
    : AbstractExecutor(exec_ctx), plan_(plan), childs_(std::move(child_executor)) {}

void SortExecutor::Init() {
  childs_->Init();
  Tuple tuple;
  RID rid;
  tuples_.clear();
  while (childs_->Next(&tuple, &rid)) {
    tuples_.emplace_back(tuple);
  }
  cur_idx_ = 0;
  SortHelper helper(GetOutputSchema(), plan_->GetOrderBy());
  std::sort(tuples_.begin(), tuples_.end(), helper);
}

auto SortExecutor::Next(Tuple *tuple, RID *rid) -> bool {
  if (cur_idx_ != tuples_.size()) {
    *rid = tuples_[cur_idx_].GetRid();
    *tuple = tuples_[cur_idx_];
    ++cur_idx_;
    return true;
  }
  return false;
}
}  // namespace bustub
